package com.thprojects.myphotomemories.controller;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;

public class LocationController {
	
	Context mContext;
    LocationManager mLocationManager;
    LocationListener mLocationListener;
    ProgressDialog mPDialog;
    OnGotLocationListener mOGLListener;

	
	public LocationController(Context context, OnGotLocationListener OGLListener) {
		mContext = context;
		
		mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
		
		mOGLListener = OGLListener;
		
		// Define a listener that responds to location updates
		mLocationListener = new LocationListener() {
			public void onLocationChanged(Location loc) {
				// Called when a new location is found by the network location
				// provider.
				gotLocation(loc);
			}

			public void onStatusChanged(String provider, int status, Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}
		};
	}
    
	public void localize(){
		//check network service
		if (!isOnline()){
			GuiController.showError(mContext, "No network service available");
			return;
		}
		
		mPDialog = ProgressDialog.show(mContext, "Localizing", "Please wait...", true);

		// Register the listener with the Location Manager to receive location updates
		mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
	}
    
    private void gotLocation(Location loc){
    	mLocationManager.removeUpdates(mLocationListener);
	      mPDialog.cancel();
	      Log.d("MPM", "location: lat="+loc.getLatitude()+", long="+loc.getLongitude());
	      askCorrectLocation(loc);
    }

	
	private void askCorrectLocation (Location l){
		Geocoder gc = new Geocoder(mContext, Locale.ITALY);
		try {
			Log.d("MPM", "getting addrs");
			//get the list of possible locations
			List<Address> addrs = gc.getFromLocation(l.getLatitude(), l.getLongitude(), 5);
			
			//show the user
			final String[] items = new String[addrs.size()];
			for (int i=0; i<addrs.size(); i++){
				String a = "";
				int mali = addrs.get(i).getMaxAddressLineIndex();
				if (mali == 0) continue;
				for (int j=0; j<mali-1; j++){
					a += addrs.get(i).getAddressLine(j)+", ";
				}
				a += addrs.get(i).getAddressLine(mali-1);
				items[i] = a;
			}

			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle("Where are you?");
			builder.setItems(items, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
					mOGLListener.onGotLocation(items[item]);
			    }
			});
			builder.create().show();
			
		} catch (IOException e) {
			Log.d("MPM", "getting addrs exception: lat="+l.getLatitude()+", long="+l.getLongitude()+", msg="+e.getMessage());
			GuiController.showError(mContext, "Can't get your location now. Please try again.");
		} catch (Exception e){
			GuiController.showError(mContext, "Can't get your location now. Please try again.");
		}
	}
	
	private boolean isOnline() {
    	ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    	if (cm==null || cm.getActiveNetworkInfo() == null) return false;
    	return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }
}
